import axios from "axios";
import { MessageBox, Message } from "element-ui";
import qs from "qs";
import hostSetting from "@/api/host-setting";
// create an axios instance
const service = axios.create({
  baseURL: hostSetting.host,
  timeout: 5000 // request timeout
});

// request interceptor  拦截器
service.interceptors.request.use(
  config => {
    if (window.localStorage.getItem("BF-ADMIN-TOKEN")) {
      // 把token添加到自定义请求头
      config.headers["bufan-token"] = localStorage.getItem("BF-ADMIN-TOKEN");
    }
    return config;
  },
  error => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data;
    return res;
  },
  error => {
    console.log("err" + error); // for debug
    Message({
      message: error.message,
      type: "error",
      duration: 5 * 1000
    });
    return Promise.reject(error);
  }
);
// 用于对service进行再次包装
function http(config) {
  // axios的默认配置 如果时get 参数需要放到 params
  // 如果是post 参数需要放到  data
  var myConfig = {
    url: config.url,
    method: config.method
  };
  if (config.method.toLowerCase() == "post") {
    myConfig.data = qs.stringify(config.params, { allowDots: true });
  } else if (config.method.toLowerCase() == "get") {
    myConfig.params = config.params;
  }

  // 区分了get和post 的配置
  return service(myConfig);
}

export default http;
